package cn.le.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock允许你尝试着获取但最终未获取锁,这样如果其他人已经获取了这个锁,
 * 那么你就可以离开去执行其它的一些事情,而不是等待直到这个锁被释放,就像在untimed()
 * 方法中所看到的.在timed()中,做出了尝试去获取锁,该尝试可以在2秒之后失败
 *
 *
 */
public class AttemptLocking {

    private ReentrantLock lock = new ReentrantLock();

    public void untimed()
    {
        boolean captured = lock.tryLock();//仅在调用时锁为空闲状态才获取该锁
        try
        {
            System.out.println("tryLock(): "+captured);
        }
        finally {
            if(captured)
            {
                lock.unlock();
            }
        }

    }

    public void timed()
    {
        boolean captured = false;
        try
        {
            //如果锁在给定等待时间内空闲,并且当前线程未被中断,则获取锁
            captured = lock.tryLock(2, TimeUnit.SECONDS);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        try {
            System.out.println("lock.tryLock(2, TimeUnit.SECONDS:)"+captured);
        }
        finally {
            if(captured)
            {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {

        final AttemptLocking al = new AttemptLocking();
        al.untimed();
        al.timed();

        new Thread()
        {
            public void run()
            {
                al.lock.lock();
                System.out.println("acquired");
            }
        }.start();
        Thread.yield();
    }


}
